<?php
namespace App\Services\Tools;

use App\Exceptions\BasicException;

class CurlService
{
    /**
     * Curl POST请求方法
     * @param $url string  请求url
     * @param array $post_data  post请求数据
     * @return mixed
     * @throws BasicException
     */
    static function curl_post($url,$post_data=array())
    {
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);

//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        //执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求头
//        curl_setopt($ch, CURLOPT_HEADER, $header);

        //设置请求方式为POST
        curl_setopt($ch, CURLOPT_POST, true);
        //post变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //输出
        $output = curl_exec($ch);


        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($code != 200) throw new BasicException(10020);

        curl_close($ch);

        return json_decode($output,true);
    }


    /**
     * Curl GET请求方法
     * @param $url  请求地址
     * @param array $get_data   get请求数据
     * @return mixed
     * @throws BasicException
     */
    public function curl_get($url,$get_data=array())
    {
        //构造请求参数
        $param = http_build_query($get_data);
        $url .= '?'.$param;
        //初始化
        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL,$url);

        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        $output = curl_exec($ch);

        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($code != 200) throw new BasicException(10020);

        curl_close($ch);

        return json_decode($output);
    }


    // 同步发送行为上报请求
    public static function actionReport($data, $isSync = false) {
        $url = env('REPORT_URL') . '/' . "service/action-hook/report";
        if ($isSync) {
            $data['is_sync'] = $isSync;
        }

        foreach ($data as $key => $item) {
            if (is_array($item)) {
                foreach ($item as $subKey => $subItem) {
                    $data[$key . "[{$subKey}]"] = $subItem;
                }
                unset($data[$key]);
            }
        }

        try {
            $result = self::curl_post($url, $data);
            return $result;
        } catch (\Exception $e) {
            app("log")->error($e->getMessage());
        }
    }


}